<template>
    <view class="draw-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <view class="back-btn" @click="goBack">
                <text class="back-icon">←</text>
            </view>
            <text class="nav-title">项目结构图绘制</text>
            <view class="action-btn" @click="saveDrawing">
                <text class="action-text">保存</text>
            </view>
        </view>
        
        <!-- 工具栏 -->
        <view class="toolbar">
            <view 
                v-for="(tool, index) in tools" 
                :key="index" 
                class="tool-item" 
                :class="{ active: currentTool === tool.type }"
                @click="selectTool(tool.type)"
            >
                <text class="tool-icon">{{ tool.icon }}</text>
                <text class="tool-name">{{ tool.name }}</text>
            </view>
        </view>
        
        <!-- 颜色选择器 -->
        <view class="color-picker">
            <view 
                v-for="(color, index) in colors" 
                :key="index" 
                class="color-item" 
                :class="{ active: currentColor === color }"
                :style="{ backgroundColor: color }"
                @click="selectColor(color)"
            ></view>
        </view>
        
        <!-- 画布区域 -->
        <view class="canvas-container">
            <canvas 
                canvas-id="drawingCanvas"
                class="drawing-canvas"
                @touchstart="onTouchStart"
                @touchmove="onTouchMove"
                @touchend="onTouchEnd"
                :style="{
                    cursor: getCursorStyle(),
                    width: canvasWidth + 'px',
                    height: canvasHeight + 'px'
                }"
            ></canvas>
        </view>
        
        <!-- 底部操作栏 -->
        <view class="bottom-bar">
            <view class="action-btn" @click="clearCanvas">
                <text class="action-icon">🗑️</text>
                <text class="action-text">清空</text>
            </view>
            <view class="action-btn" @click="undoLastAction" :class="{ disabled: !canUndo }">
                <text class="action-icon">↩️</text>
                <text class="action-text">撤销</text>
            </view>
            <view class="action-btn" @click="saveDrawing">
                <text class="action-icon">💾</text>
                <text class="action-text">保存到订单</text>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

// 画布上下文
const canvasContext = ref(null);
// 当前选中的工具
const currentTool = ref('pen');
// 当前选中的颜色
const currentColor = ref('#A259FF');
// 线条宽度
const lineWidth = ref(3);
// 是否正在绘制
const isDrawing = ref(false);
// 上一个点的坐标
const lastPoint = ref({ x: 0, y: 0 });
// 绘制历史记录
const drawHistory = ref([]);
// 当前历史记录索引
const historyIndex = ref(-1);
// 是否可以撤销
const canUndo = ref(false);

// 工具列表
const tools = [
    { type: 'pen', name: '画笔', icon: '✏️' },
    { type: 'line', name: '直线', icon: '⎯' },
    { type: 'rect', name: '矩形', icon: '□' },
    { type: 'circle', name: '圆形', icon: '○' },
    { type: 'text', name: '文字', icon: 'T' },
    { type: 'eraser', name: '橡皮', icon: '🧽' }
];

// 颜色列表
const colors = [
    '#A259FF', '#6069f0', '#10AEFF', '#ffffff', 
    '#ff4444', '#ff8800', '#00cc00', '#000000'
];

// 画布尺寸
const canvasWidth = ref(0);
const canvasHeight = ref(0);

// 初始化画布
onMounted(() => {
    // 获取设备信息
    const sysInfo = uni.getSystemInfoSync();
    // 设置画布尺寸，减去边距
    canvasWidth.value = sysInfo.windowWidth - 40; // 减去左右边距
    canvasHeight.value = sysInfo.windowHeight * 0.6; // 画布高度为屏幕高度的60%
    
    // 获取画布上下文
    canvasContext.value = uni.createCanvasContext('drawingCanvas');
    
    // 设置默认样式
    canvasContext.value.setStrokeStyle(currentColor.value);
    canvasContext.value.setLineWidth(lineWidth.value);
    canvasContext.value.setLineCap('round');
    canvasContext.value.setLineJoin('round');
    
    // 绘制白色背景
    canvasContext.value.setFillStyle('#ffffff');
    canvasContext.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value);
    canvasContext.value.draw(true);
    
    // 延迟一下再保存初始状态，确保画布已经渲染
    setTimeout(() => {
        saveToHistory();
    }, 300);
});

// 选择工具
const selectTool = (tool) => {
    currentTool.value = tool;
};

// 选择颜色
const selectColor = (color) => {
    currentColor.value = color;
    if (canvasContext.value) {
        canvasContext.value.setStrokeStyle(color);
        canvasContext.value.setFillStyle(color);
    }
};

// 获取光标样式
const getCursorStyle = () => {
    switch (currentTool.value) {
        case 'pen':
            return 'crosshair';
        case 'eraser':
            return 'cell';
        case 'text':
            return 'text';
        default:
            return 'default';
    }
};

// 触摸开始事件
const onTouchStart = (e) => {
    const touch = e.touches[0];
    const x = touch.x;
    const y = touch.y;
    
    isDrawing.value = true;
    lastPoint.value = { x, y };
    
    if (currentTool.value === 'pen' || currentTool.value === 'eraser') {
        canvasContext.value.beginPath();
        canvasContext.value.moveTo(x, y);
        
        if (currentTool.value === 'eraser') {
            canvasContext.value.setStrokeStyle('#ffffff');
            canvasContext.value.setLineWidth(20);
        } else {
            canvasContext.value.setStrokeStyle(currentColor.value);
            canvasContext.value.setLineWidth(lineWidth.value);
        }
    }
};

// 触摸移动事件
const onTouchMove = (e) => {
    if (!isDrawing.value) return;
    
    const touch = e.touches[0];
    const x = touch.x;
    const y = touch.y;
    
    if (currentTool.value === 'pen' || currentTool.value === 'eraser') {
        canvasContext.value.lineTo(x, y);
        canvasContext.value.stroke();
        canvasContext.value.draw(true);
    }
};

// 触摸结束事件
const onTouchEnd = (e) => {
    if (!isDrawing.value) return;
    
    const x = lastPoint.value.x;
    const y = lastPoint.value.y;
    
    if (currentTool.value === 'line') {
        const touch = e.changedTouches[0];
        canvasContext.value.beginPath();
        canvasContext.value.moveTo(x, y);
        canvasContext.value.lineTo(touch.x, touch.y);
        canvasContext.value.setStrokeStyle(currentColor.value);
        canvasContext.value.setLineWidth(lineWidth.value);
        canvasContext.value.stroke();
        canvasContext.value.draw(true);
    } else if (currentTool.value === 'rect') {
        const touch = e.changedTouches[0];
        const width = touch.x - x;
        const height = touch.y - y;
        canvasContext.value.beginPath();
        canvasContext.value.setStrokeStyle(currentColor.value);
        canvasContext.value.setLineWidth(lineWidth.value);
        canvasContext.value.rect(x, y, width, height);
        canvasContext.value.stroke();
        canvasContext.value.draw(true);
    } else if (currentTool.value === 'circle') {
        const touch = e.changedTouches[0];
        const radius = Math.sqrt(Math.pow(touch.x - x, 2) + Math.pow(touch.y - y, 2));
        canvasContext.value.beginPath();
        canvasContext.value.setStrokeStyle(currentColor.value);
        canvasContext.value.setLineWidth(lineWidth.value);
        canvasContext.value.arc(x, y, radius, 0, 2 * Math.PI);
        canvasContext.value.stroke();
        canvasContext.value.draw(true);
    } else if (currentTool.value === 'text') {
        // 在实际应用中，这里应该弹出一个输入框让用户输入文字
        uni.showModal({
            title: '输入文字',
            editable: true,
            placeholderText: '请输入要添加的文字',
            success: (res) => {
                if (res.confirm && res.content) {
                    canvasContext.value.setFontSize(24);
                    canvasContext.value.setFillStyle(currentColor.value);
                    canvasContext.value.fillText(res.content, x, y);
                    canvasContext.value.draw(true);
                    saveToHistory();
                }
            }
        });
    }
    
    isDrawing.value = false;
    
    // 保存当前状态到历史记录
    if (currentTool.value !== 'text') {  // 文本工具在输入完成后保存
        saveToHistory();
    }
};

// 保存当前状态到历史记录
const saveToHistory = () => {
    // 获取画布数据
    uni.canvasToTempFilePath({
        canvasId: 'drawingCanvas',
        width: canvasWidth.value,
        height: canvasHeight.value,
        destWidth: canvasWidth.value * 2, // 提高图片质量
        destHeight: canvasHeight.value * 2,
        success: (res) => {
            // 如果当前不是最新历史，则移除后面的历史
            if (historyIndex.value < drawHistory.value.length - 1) {
                drawHistory.value = drawHistory.value.slice(0, historyIndex.value + 1);
            }
            
            // 添加到历史记录
            drawHistory.value.push(res.tempFilePath);
            historyIndex.value = drawHistory.value.length - 1;
            canUndo.value = historyIndex.value > 0;
        },
        fail: (err) => {
            console.error('保存历史记录失败:', err);
        }
    });
};

// 撤销上一步操作
const undoLastAction = () => {
    if (historyIndex.value > 0) {
        historyIndex.value--;
        
        // 从历史记录中恢复
        uni.getImageInfo({
            src: drawHistory.value[historyIndex.value],
            success: (res) => {
                // 确保图片有效
                if (res && res.width > 0 && res.height > 0) {
                    // 先清空画布
                    canvasContext.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
                    // 绘制恢复的图像
                    canvasContext.value.drawImage(res.path, 0, 0, canvasWidth.value, canvasHeight.value);
                    canvasContext.value.draw();
                    canUndo.value = historyIndex.value > 0;
                } else {
                    uni.showToast({
                        title: '撤销失败，图像无效',
                        icon: 'none'
                    });
                    // 回滚历史记录索引
                    historyIndex.value++;
                }
            },
            fail: (err) => {
                console.error('获取历史图像失败:', err);
                // 回滚历史记录索引
                historyIndex.value++;
                uni.showToast({
                    title: '撤销失败，请重试',
                    icon: 'none'
                });
            }
        });
    }
};

// 清空画布
const clearCanvas = () => {
    uni.showModal({
        title: '确认清空',
        content: '确定要清空画布吗？此操作不可撤销。',
        success: (res) => {
            if (res.confirm) {
                canvasContext.value.setFillStyle('#ffffff');
                canvasContext.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value);
                canvasContext.value.draw();
                
                // 保存清空后的状态
                setTimeout(() => {
                    saveToHistory();
                }, 100);
            }
        }
    });
};

// 保存绘图
const saveDrawing = () => {
    uni.showLoading({
        title: '保存中...'
    });
    
    // 确保画布尺寸正确
    console.log('画布尺寸:', canvasWidth.value, canvasHeight.value);
    
    // 延迟一点执行，确保画布准备好
    setTimeout(() => {
        uni.canvasToTempFilePath({
            canvasId: 'drawingCanvas',
            width: canvasWidth.value,
            height: canvasHeight.value,
            destWidth: canvasWidth.value * 2, // 提高图片质量
            destHeight: canvasHeight.value * 2,
            fileType: 'png',
            quality: 1,
            success: (res) => {
                // 获取服务器基础URL
                const baseUrl = uni.getStorageSync('baseUrl') || 'http://127.0.0.1:8080';
                const uploadUrl = `${baseUrl}/system/uploadImg`;
                
                console.log('生成临时图片成功:', res.tempFilePath);
                
                // 上传图片
                uni.uploadFile({
                    url: uploadUrl,
                    filePath: res.tempFilePath,
                    name: 'file',
                    header: {
                        'sa-token': uni.getStorageSync('sa-token')
                    },
                    success: (uploadRes) => {
                        try {
                            const result = JSON.parse(uploadRes.data);
                            if (result.code === 200) {
                                uni.showToast({
                                    title: '保存成功',
                                    icon: 'success'
                                });
                                
                                // 直接将图片URL添加到订单表单
                                const pages = getCurrentPages();
                                const prevPage = pages[pages.length - 2];
                                
                                // 将图片URL存储到全局变量
                                getApp().globalData = getApp().globalData || {};
                                
                                // 确保图片URL是完整的
                                let imageUrl = result.data;
                                // 如果返回的是相对路径，添加服务器基础URL
                                if (imageUrl && !imageUrl.startsWith('http')) {
                                    // 检查是否已经包含baseUrl
                                    if (!imageUrl.includes(baseUrl)) {
                                        imageUrl = baseUrl + imageUrl;
                                    }
                                }
                                
                                getApp().globalData.drawImage = imageUrl;
                                
                                console.log('图片已保存到全局变量', imageUrl);
                                
                                // 返回上一页
                                setTimeout(() => {
                                    uni.navigateBack();
                                }, 1000);
                            } else {
                                uni.showToast({
                                    title: result.msg || '保存失败',
                                    icon: 'none'
                                });
                            }
                        } catch (e) {
                            console.error('解析上传结果失败:', e);
                            uni.showToast({
                                title: '保存失败，请重试',
                                icon: 'none'
                            });
                        }
                    },
                    fail: (error) => {
                        console.error('上传失败:', error);
                        uni.showToast({
                            title: '上传失败，请重试',
                            icon: 'none'
                        });
                    },
                    complete: () => {
                        uni.hideLoading();
                    }
                });
            },
            fail: (error) => {
                console.error('生成图片失败:', error);
                uni.hideLoading();
                uni.showToast({
                    title: '生成图片失败，请重试',
                    icon: 'none'
                });
            }
        });
    }, 300);
};

// 返回上一页
const goBack = () => {
    uni.showModal({
        title: '确认返回',
        content: '返回将丢失未保存的绘图，确定要返回吗？',
        success: (res) => {
            if (res.confirm) {
                uni.navigateBack();
            }
        }
    });
};
</script>

<style lang="scss" scoped>
.draw-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #18122B 0%, #120C1C 100%);
    display: flex;
    flex-direction: column;
}

/* 导航栏样式 */
.nav-bar {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #2D1457;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}

.back-icon {
    font-size: 40rpx;
    color: #A259FF;
}

.nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #A259FF;
}

.action-btn {
    padding: 10rpx 20rpx;
    background: rgba(123, 47, 242, 0.2);
    border-radius: 30rpx;
    display: flex;
    align-items: center;
}

.action-text {
    font-size: 28rpx;
    color: #A259FF;
}

/* 工具栏样式 */
.toolbar {
    display: flex;
    justify-content: space-around;
    padding: 20rpx;
    background: rgba(45, 20, 87, 0.3);
    border-bottom: 1rpx solid #2D1457;
}

.tool-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10rpx 20rpx;
    border-radius: 12rpx;
}

.tool-item.active {
    background: rgba(123, 47, 242, 0.3);
    border: 1px solid #7B2FF2;
}

.tool-icon {
    font-size: 36rpx;
    color: #A259FF;
    margin-bottom: 10rpx;
}

.tool-name {
    font-size: 24rpx;
    color: #B8B8D1;
}

/* 颜色选择器样式 */
.color-picker {
    display: flex;
    justify-content: space-around;
    padding: 20rpx;
    background: rgba(45, 20, 87, 0.2);
    border-bottom: 1rpx solid #2D1457;
}

.color-item {
    width: 60rpx;
    height: 60rpx;
    border-radius: 30rpx;
    border: 2rpx solid #2D1457;
}

.color-item.active {
    border: 4rpx solid #ffffff;
    transform: scale(1.1);
}

/* 画布样式 */
.canvas-container {
    flex: 1;
    padding: 20rpx;
    background: #ffffff;
    border-radius: 16rpx;
    margin: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

.drawing-canvas {
    background: #ffffff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    border-radius: 8rpx;
}

/* 底部操作栏 */
.bottom-bar {
    display: flex;
    justify-content: space-around;
    padding: 20rpx;
    background: rgba(45, 20, 87, 0.3);
    border-top: 1rpx solid #2D1457;
}

.action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.action-btn.disabled {
    opacity: 0.5;
}

.action-icon {
    font-size: 40rpx;
    margin-bottom: 10rpx;
}

.action-text {
    font-size: 24rpx;
    color: #B8B8D1;
}
</style>